package com.sprite.framework.start;

import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import com.sprite.framework.start.util.ContainerUtils;
import com.sprite.utils.UtilXml;

public final class Start {
	private static Logger logger = LoggerFactory.getLogger(Start.class);
	
	
	public static void main(String[] args)  {
		Loader loader = new Loader();
		
		String cmd = "start";
		
		if(args.length >0) {
			cmd = args[0];
		}
		
		try {
			URL url = ContainerUtils.readConfigUrl();
			
			if(url == null) {
				logger.error("not found config file");
				return;
			}
			
			Document document = UtilXml.readXmlDocument(url);
			
			loader.init(document, args);
			
			if("start".equalsIgnoreCase(cmd)) {
				loader.start();
				if(loader.isSafeShutdown()) {
					loader.awaitToStop();
					logger.info("exit jvm");
					System.exit(0);
				}else{
					Runtime.getRuntime().addShutdownHook(new Thread() {
						public void run() {
							loader.stop();
							logger.info("exit jvm");
							System.exit(0);
						}
					});
				}
				
			}else if("stop".equalsIgnoreCase(cmd)){
				loader.stopLoader();
			}else {
				logger.error("not found command :", cmd);
			}
			
		} catch (Exception e) {
			logger.error("start error", e);
			loader.stop();
			return;
		} 
	
	}
	
}
